import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/entity/company_info_entity.dart';
import 'package:nyh_motorcade_app/http/http_address.dart';
import 'package:nyh_motorcade_app/http/http_manager.dart';
import 'package:nyh_motorcade_app/routes/routes.dart';
import 'package:nyh_motorcade_app/utils/sp_utils.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';

class CompanyManageController extends GetxController {
  MultiState multiState = MultiState.loading;
  TextEditingController quotaController = TextEditingController();
  FocusNode quotaFocus = FocusNode();

  CompanyInfoEntity? companyInfoEntity;
  double totalAmount = 0.0;
  double companyAmount = 0.0;
  double motorcadeAmount = 0.0;
  double cardAmount = 0.0;

  bool isBalanceReminder = false;
  double quota = 0.0;

  @override
  void onReady() {
    super.onReady();
    getCompanyInfo();
  }

  void onRetry() {
    multiState = MultiState.loading;
    update();
    getCompanyInfo();
  }

  void changeBalanceReminderState(bool value) {
    isBalanceReminder = value;
    if (!isBalanceReminder) {
      quota = 0.0;
      quotaController.text = "";
      setBalanceReminder(isOpen: false);
    }
    update();
  }

  void setQuota(String value) {
    if (value.isEmpty) {
      quota = 0.0;
    } else {
      quota = double.parse(value);
    }
    update();
  }

  Future<void> getCompanyInfo() async {
    httpManager.post(
      Get.context,
      HttpAddress.GET_COMPANY_INFO,
      {"superId": await SPUtils.getString(SPUtils.COMPANY_ID)},
      isToast: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          multiState = MultiState.fail;
          update();
          return;
        }
        companyInfoEntity = CompanyInfoEntity().fromJson(data);
        totalAmount = companyInfoEntity!.totalAmount ?? 0.0;
        List<CompanyInfoAmountDetail> amountDetailList = companyInfoEntity!.amountDetail ?? [];
        if (amountDetailList.isNotEmpty) {
          amountDetailList.forEach((element) {
            switch (element.type ?? "") {
              case "COMPANY":
                companyAmount = element.amount ?? 0.0;
                break;
              case "MOTORCADE":
                motorcadeAmount = element.amount ?? 0.0;
                break;
              case "CARD":
                cardAmount = element.amount ?? 0.0;
                break;
              default:
            }
          });
        }
        isBalanceReminder = companyInfoEntity?.ifWarnSwitch == 1;
        quota = companyInfoEntity?.warnAmount ?? 0.0;
        if (quota > 0.0) {
          quotaController.text = quota.toString();
        }
        multiState = MultiState.success;
        update();
      },
      onFail: (code, msg) {
        multiState = MultiState.fail;
        update();
      },
      onError: (msg) {
        multiState = MultiState.error;
        update();
      },
    );
  }

  void setBalanceReminder({bool isOpen = true}) {
    if (isOpen) {
      if (!isBalanceReminder || quota <= 0.0) {
        return;
      }
    }
    quotaFocus.unfocus();
    httpManager.post(
      Get.context,
      HttpAddress.SET_BALANCE_REMINDER,
      {
        "superId": companyInfoEntity!.id,
        "ifWarnSwitch": isBalanceReminder ? 1 : 0,
        "warnAmount": quota,
      },
      isToast: true,
      isLoadingDialog: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          return;
        }
        if (data is bool) {
          if (!data) {
            ToastUtils.toast("设置失败");
            return;
          }
          ToastUtils.toast("设置成功");
        }
      },
    );
  }

  void goToCompanySettlementPage() {
    Get.toNamed(Routes.companySettlement, arguments: {
      Constant.PARAM_COMPANY_ID: companyInfoEntity?.id ?? "",
      Constant.PARAM_COMPANY_NAME: companyInfoEntity?.name ?? "",
      Constant.PARAM_COMPANY_AMOUNT: companyAmount,
    });
  }

  void goToCashFlowPage() {
    Get.toNamed(Routes.cashFlow, arguments: companyInfoEntity?.id ?? "");
  }
}
